var table;
$(function () {
    loadTable();
});

function loadTable() {
    var answer = $("#answers").val();
    var audio = $('#audio').val();
    var data = {"answer": answer,"voicetext": audio};
    table = $("#answerList").DataTable({
        ajax: {
            url: baseQuestionUrl + "list/answer",
            headers: {
                "authorization": 'Bearer ' + getCookie(cookieName)
            },
            type: "GET",
            contentType: "application/json",
            data: function (req) {
                req.limit = req.length;
                req.answer = data.answer
                req.voicetext = data.voicetext
            },
            dataSrc: function (res) {
                res.recordsTotal = res.data.total;
                res.recordsFiltered = res.data.total;
                return res.data.rows;
            },
            error: function (request, error) {
                if (request.status === 401) {
                    $(location).attr('href', 'login.html');
                } else {
                    swal("失败");
                }
            }
        },
        serverSide: true,
        // data: data,
        destroy: true,
        bLengthChange: false,
        searching: false,
        ordering: false,
        select: false,
        columns: [
            {data: 'answer'},
            {data: 'voicetext'},
            {data: 'created'},
            {data: 'updated'}
        ],
        pagingType: "full_numbers",
        language: {
            "sProcessing": "处理中...",
            "sLengthMenu": "显示 _MENU_ 项结果",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
            "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            oAria: {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },
        columnDefs: [
            {
                targets: 2,
                render: function (data, type, row, meta) {
                    var time = new Date(row.created);
                    var y = time.getFullYear();
                    var m = time.getMonth()+1;
                    var d = time.getDate();
                    var h = time.getHours();
                    var mm = time.getMinutes();
                    var s = time.getSeconds();
                    return y+'-'+m+'-'+d+' '+h+':'+mm+':'+s;
                }
            },
            {
                targets: 3,
                render: function (data, type, row, meta) {
                    var time = new Date(row.updated);
                    var y = time.getFullYear();
                    var m = time.getMonth()+1;
                    var d = time.getDate();
                    var h = time.getHours();
                    var mm = time.getMinutes();
                    var s = time.getSeconds();
                    return y+'-'+m+'-'+d+' '+h+':'+mm+':'+s;
                }
            },
            {
            targets: 4,
            render: function (data, type, row) {
                return "<button type='button' style='margin-right: 10px;border: 1px solid #0D1113;color: #0D1113;background: transparent;' class='btn btn-primary' onclick='edit(" + JSON.stringify(row) + ");'>编辑</button><button type='button' class='btn btn-danger' style='margin-right: 10px;border: 1px solid red;color: red;background: transparent;' onclick='del(" + JSON.stringify(row) + ");'>删除</button>";
            }
        }]
    });
}


/**
 * 查询按钮点击事件
 */
function queryData() {
    loadTable()
}

/**
 * 清除搜索条件
 */
function clearSelect() {
    $("#answers").val("");
    $("#audio").val("");
    loadTable();
}

function edit(row){
    if(!row) {
        sessionStorage.removeItem('id');
        initPage('answer', 'answer/edit.html')
    }else{
        sessionStorage.setItem('id', row.id);
        initPage('answer', 'answer/edit.html?id='+row.id)
    }
}

/**
 * 答案删除
 * @param row
 */
function del(row){
    console.log(row)
    if(row.questionid){
        swal({
            title : "删除答案",
            text : "该答案正在被引用，不能直接删除，请先解绑。",
            type : "error",
            showCancelButton : false,
            confirmButtonColor : '#337ab7',
            confirmButtonText : "知道了",
            closeOnConfirm : false
        })
    }else{
        swal({
            title: "删除答案",
            text: "确认要删除该答案吗？",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#337ab7",
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            closeOnConfirm: false,
            closeOnCancel: true
        },
        function(isConfirm){
            if (isConfirm) {
                var url=baseQuestionUrl + "deleteanswer/"+row.id
                ajaxCommon.request('delete',url,{},function (res) {
                    console.log(res)
                    if(res.code===200) {
                        swal("删除！", "当前记录已被删除！", "success");
                        loadTable()
                    }
                })
            }
        });
    }
}
